package com.example.exam.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

/**
 * @author zhang
 */
@Component
@Log4j2
public class JsonUtils<T> {
    @SneakyThrows
    public String t2String(T t) {
        ObjectMapper om = new ObjectMapper();
        return om.writeValueAsString(t);
    }

    @SneakyThrows
    public T string2t(String json, Class<T> clazz) {
        ObjectMapper om = new ObjectMapper();
        return om.readValue(json, clazz);
    }

    public static String o2s(Object o) {
        ObjectMapper om = new ObjectMapper();
        try {
            return om.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("json转化异常:[]", e);
        }
        return null;
    }

    public static Object s2o(String json, Class<?> clazz) {
        try {
            ObjectMapper om = new ObjectMapper();
            return om.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error("json解析错误:[]", e);
            return null;
        }
    }

}
